# import BunnyCDNStorage
# import os
#
#
# def upload_file(file_path, cdn_path, file_name):
#     AccessKey = "db805d54-70e4-458c-bdc06ba6ddb4-f1eb-4f64"
#     cdn_connector = BunnyCDNStorage.CDNConnector(AccessKey, 'web-apkpoki')
#     res = cdn_connector.upload_file(cdn_path, file_name, file_path)
#     if res['HttpCode'] == 201:
#         return True
#     else:
#         print(res)
#         return False


import os
import requests


def upload_file(file_path, cdn_path, file_name):
    REGION = 'us'  # If German region, set this to an empty string: ''
    STORAGE_ZONE_NAME = 'web-apkpoki'
    # FILENAME_EXTENSION = '/demo/file.txt'
    FILENAME_EXTENSION = cdn_path + file_name
    ACCESS_KEY = 'db805d54-70e4-458c-bdc06ba6ddb4-f1eb-4f64'
    FILE_PATH = file_path

    base_url = "storage.bunnycdn.com"
    if REGION:
        base_url = f"{REGION}.{base_url}"

    url = f"https://{base_url}/{STORAGE_ZONE_NAME}/{FILENAME_EXTENSION}"

    headers = {
        "AccessKey": ACCESS_KEY,
        "Content-Type": "application/octet-stream",
        "accept": "application/json"
    }

    try:
        with open(FILE_PATH, 'rb') as file_data:
            response = requests.put(url, headers=headers, data=file_data)
        if response.status_code == 201:
            return True
        else:
            print(response)
            return False
    except Exception:
        return False


def upload(path, num, addr='game', filename=''):
    if os.access(path, os.F_OK):
        try:
            res = upload_file(path, addr, filename)
            if res == True:
                with open('file.txt', 'a') as w:
                    w.write('第' + str(num) + '个文件->' + filename + '<-已上传完成-------->' + filename + '\n')
                    w.close()
                print('第' + str(num) + '个文件->' + filename + '<-已上传完成')
                os.remove(path)
                return True
            else:
                with open('file_error.txt', 'a') as w:
                    w.write('第' + str(num) + '个文件->' + filename + '<-上传失败-------->' + filename + '\n')
                    w.close()
                print('第' + str(num) + '个文件->' + filename + '<-上传失败-------->' + filename)
                os.remove(path)
                return False
        except Exception:
            with open('file_error.txt', 'a') as w:
                w.write('第' + str(num) + '个文件->' + filename + '<-上传失败-------->' + filename + '\n')
                w.close()
            print('第' + str(num) + '个文件->' + filename + '<-上传失败-------->' + filename)
            os.remove(path)
            return False
        os.remove(path)